"""
文件上传相关路由
"""

import os
import uuid
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.common import StandardResponse
from services.auth_service import get_current_user
from services.upload_service import UploadService
from config import get_settings

router = APIRouter(prefix="/upload", tags=["文件上传"])
settings = get_settings()

@router.post("/avatar", response_model=StandardResponse, summary="头像上传")
async def upload_avatar(
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    上传用户头像
    
    - **file**: 头像文件（支持jpg, jpeg, png, gif格式）
    """
    try:
        upload_service = UploadService()
        
        # 验证文件类型
        if not upload_service.validate_image_file(file):
            raise HTTPException(
                status_code=400,
                detail="不支持的文件格式，请上传jpg、jpeg、png或gif格式的图片"
            )
        
        # 验证文件大小
        if not upload_service.validate_file_size(file, max_size=5*1024*1024):  # 5MB
            raise HTTPException(
                status_code=400,
                detail="文件大小不能超过5MB"
            )
        
        # 上传文件
        file_info = await upload_service.upload_avatar(file, current_user["id"])
        
        return StandardResponse(
            success=True,
            message="头像上传成功",
            data=file_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"头像上传失败: {str(e)}"
        )

@router.post("/files", response_model=StandardResponse, summary="通用文件上传")
async def upload_files(
    files: List[UploadFile] = File(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    通用文件上传
    
    - **files**: 文件列表
    """
    try:
        upload_service = UploadService()
        uploaded_files = []
        
        for file in files:
            # 验证文件类型
            if not upload_service.validate_file_extension(file):
                raise HTTPException(
                    status_code=400,
                    detail=f"不支持的文件格式: {file.filename}"
                )
            
            # 验证文件大小
            if not upload_service.validate_file_size(file):
                raise HTTPException(
                    status_code=400,
                    detail=f"文件大小超出限制: {file.filename}"
                )
            
            # 上传文件
            file_info = await upload_service.upload_file(file, current_user["id"])
            uploaded_files.append(file_info)
        
        return StandardResponse(
            success=True,
            message=f"成功上传{len(uploaded_files)}个文件",
            data=uploaded_files
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"文件上传失败: {str(e)}"
        )

@router.delete("/files/{file_id}", response_model=StandardResponse, summary="删除文件")
async def delete_file(
    file_id: str,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    删除文件
    
    - **file_id**: 文件ID
    """
    try:
        upload_service = UploadService()
        await upload_service.delete_file(file_id, current_user["id"])
        
        return StandardResponse(
            success=True,
            message="文件删除成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"文件删除失败: {str(e)}"
        )